﻿using ExamWeek01.Domain;
using ExamWeek01.Repository;
using ExamWeek01.Service.IService;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExamWeek01.Service.Service
{
    /// <summary>
    /// 用户服务实现
    /// </summary>
    public class UserService : BaseService<User>, IUserService
    {
        /// <summary>
        /// 上下文
        /// </summary>
        UserDbContext db;
        /// <summary>
        /// 日志
        /// </summary>
        ILogger<UserService> logger;
        /// <summary>
        /// 方法
        /// </summary>
        /// <param name="db">上下文</param>
        public UserService(UserDbContext db, ILogger<UserService> logger) : base(db)
        {
            this.db = db;
            this.logger = logger;
        }
        /// <summary>
        /// 用户列表显示
        /// </summary>
        /// <param name="uName">用户名</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页码</param>
        /// <param name="totalCount">总页数</param>
        /// <param name="listCount">总条数</param>
        /// <returns>列表显示</returns>
        public object GetUser(string uName, int pageIndex, int pageSize, out int totalCount, out int listCount)
        {
            try
            {
                var list = (from a in db.User
                            join b in db.UserRole
                            on a.UId equals b.UId
                            join c in db.Role
                            on b.RId equals c.RId
                            select new {
                                a.UId,
                                a.UName,
                                a.Account,
                                a.Gender,
                                a.Img,
                                c.RName
                            }).ToList();
                if (!string.IsNullOrEmpty(uName))
                {
                    list = list.Where(x => x.UName.Contains(uName)).ToList();
                }
                totalCount = list.Count;
                listCount = (int)Math.Ceiling((pageIndex * 1.0) / pageSize);
                list = list.OrderBy(x => x.UId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list;
            }
            catch (Exception ex)
            {
                logger.LogError("获取角色列表出错" + ex.Message);
                throw;
            }
        }
    }
}
